const router = require('koa-router')()
const mongoose = require('mongoose')
const statsfn = require('../lib/statsfn')
const crypto=require('crypto')
const Comment = mongoose.model('Comment')
const Image = mongoose.model('Image')

const User = mongoose.model('User')
router.get('/', async (ctx, next) => {
  const images = await Image.find({})
    .sort({createdAt: -1}).limit(20)
  const stats = await statsfn()
  console.log(stats)
  const comments  = await Comment.find({})
        .sort({createdAt:-1})
        .limit(3)
  const nearimage = await Image.find({_id:[comments[0].image,comments[1].image,comments[2].image]})
  
  console.log("评论："+comments)
  //console.log("img："+nearimage)
  await ctx.render('index', {
    title: '图片共享', images,nearimage, comments,stats,user: ctx.session.user,imginfo:ctx.session.imginfo
  })
})

router.get('/login', async ctx => {
  await ctx.render('login')
})

router.post('/login', async ctx => {
  const {username, password} = ctx.request.body
  const hashpassword = crypto.createHmac('md5',password).digest('hex');
  console.log('-------' + hashpassword)
 
  const user = await User.find({"username":username})
  console.log('-------' + user)
  if(username == null || user == null){
    console.log('用户不存在')
  }else{
    console.log('登录成功' + user[0].password)
    if(user[0].password == hashpassword){
      ctx.session.user = {username}
      console.log('-------' + user)
      ctx.redirect('/')
    }else{
      console.log('登录失败')
    }
  }


  
})

router.get('/logout', async ctx => {
  ctx.session.user = undefined
  ctx.redirect('/')
})

router.get('/register', async ctx => {
  await ctx.render('register')
})
router.post('/register', async ctx => {
  const {username, password} = ctx.request.body
  nickname=username
  
  const hashpassword = crypto.createHmac('md5',password).digest('hex');
  console.log(hashpassword)
  const user = await User.create({
    "username":username,"password":hashpassword,nickname
  })
  
  ctx.session.user = {nickname: username, username: username}
  ctx.redirect(`../`)
})

module.exports = router
